package com.xiaochong.tir.common.util;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class MathUtils {

    public static boolean isNumeric(String s) {

        if (StringUtils.isBlank(s)) {
            return false;
        }
        try {
            BigDecimal b = new BigDecimal(s);
        }catch (NumberFormatException e){
            return false;
        }

        return true;
    }


    public static boolean isNotNumeric(String s) {
        if(null == s){
            return true;
        }
        return !MathUtils.isNumeric(s);
    }

    /**
     * 保留几位有效数字
     * @param scale
     * @return
     */
    public static String roundToSignificantFigures(double oldDouble, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException(
                    "scale指定的精度为非负值");
        }

        RoundingMode rMode =null;
        //rMode=RoundingMode.FLOOR;
        //下面这种情况，其实和FLOOR一样的。
        if(oldDouble>0){
            rMode=RoundingMode.DOWN;
        }else{
            rMode=RoundingMode.UP;
        }
        //此处的scale表示的是，几位有效位数
        BigDecimal b = new BigDecimal(Double.toString(oldDouble),new MathContext(scale,rMode));
        return b.toString();
    }
}
